// PDF 解析编辑工具库
import { PDFDocument } from "pdf-lib";

// 开始结束页码数组
export function range(start, end) {
  let length = end - start + 1;
  return Array.from({ length }, (_, i) => start + i - 1);
}

// 文件转换
export function readFileAsync(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.onload = () => {
      resolve(reader.result);
    };
    reader.onerror = reject;
    reader.readAsArrayBuffer(file);
  });
}

// 添加新的 page
export async function extractPdfPage(arrayBuff) {
  const pdfSrcDoc = await PDFDocument.load(arrayBuff);
  const pdfNewDoc = await PDFDocument.create();
  console.log("pdfSrcDoc", pdfSrcDoc);
  const pages = await pdfNewDoc.copyPages(pdfSrcDoc, range(2, 3));
  pages.forEach((page) => pdfNewDoc.addPage(page));
  const newpdf = await pdfNewDoc.save();
  return newpdf;
}

// ArrayBuffer 格式转换 bold
export function renderPdf(uint8array) {
  const tempblob = new Blob([uint8array], {
    type: "application/pdf",
  });
  const docUrl = URL.createObjectURL(tempblob);
  return docUrl;
}
